<?php
class AnCurl
{
    /**
     * 执行请求
     * @param string $url    请求的url
     * @param string $type   请求类型 支持 get post
     * @param array  $data   传递的参数
     */
    public static function exec($url, $type, $data) {
        $curlHandle = curl_init();
        $type = strtolower($type);
        curl_setopt($curlHandle, CURLOPT_URL, $url);
        $data = self::encodeData($data);
        if (strtolower($type) == 'get') {
            curl_setopt($curlHandle, CURLOPT_URL, $url.'?'.$data);
            curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curlHandle, CURLOPT_HEADER, 0);
            curl_setopt($curlHandle, CURLOPT_HTTPGET, 1);
            curl_setopt($curlHandle,  CURLOPT_FOLLOWLOCATION, 1);
        } else if ($type == 'post') {
            curl_setopt($curlHandle, CURLOPT_URL, $url);
            curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curlHandle, CURLOPT_POST, 1);
            curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curlHandle,  CURLOPT_FOLLOWLOCATION, 1);
        } else {
            curl_close($curlHandle);
        }

        $result =  curl_exec($curlHandle);
        if (!$result) {
            return curl_error($curlHandle);
        }

        curl_close($curlHandle);
        return $result;
    }

    private static function encodeData($data) {
        $str = '';
        if (is_array($data)) {
            foreach ($data as $k=>$v) {
                $str =$str."$k=".urlencode($v).'&';
            }
        }
        return $str;
    }
}
?>